package com.gl.controller.meeting;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gl.pojo.dto.AdminMeetingPageDto;
import com.gl.pojo.dto.MeetingPageDto;
import com.gl.pojo.entity.File;
import com.gl.pojo.entity.Meeting;
import com.gl.pojo.Result;
import com.gl.pojo.vo.MeetingVo;
import com.gl.service.FileService;
import com.gl.service.MeetingService;
import com.gl.utils.xunfeiUtil.EncryptUtil;
import com.gl.utils.xunfeiUtil.TranslatateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.SignatureException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.gl.utils.xunfeiUtil.TranslatateUtil.APPID;
import static com.gl.utils.xunfeiUtil.TranslatateUtil.SECRET_KEY;

@RestController
@RequestMapping("/meeting")
@CrossOrigin("*")
public class MeetingController {

    @Autowired
    private MeetingService meetingService;
    @Autowired
    private FileService fileService;

    /**
     * 创建会议
     */
    @PostMapping("/create")
    public Result createMeeting(@RequestBody Meeting meeting) {
        String res = meetingService.createMeeting(meeting);
        if (res != null) {
            return Result.success(res);
        }
        return Result.error("创建会议失败");
    }

    /**
     * 修改会议信息
     */
    @PostMapping("/updateInfo")
    public Result updateMeeting(Meeting meeting) {
        int result = meetingService.updateMeeting(meeting);
        if (result > 0) {
            return Result.success();
        }
        return Result.error("修改会议信息失败");
    }

    /**
     * 删除会议
     * @param meetingId 会议ID
     * @return -
     */
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") String meetingId) {
        int result = meetingService.delete(meetingId);
        if (result > 0) {
            return Result.success();
        }
        return Result.error("删除会议失败");
    }

    /**
     * 获取会议信息
     */
    @GetMapping("/getInfo")
    public Result getMeetingInfo(@RequestParam(value = "id") String meetingId) {
        Meeting meeting = meetingService.getMeetingInfo(meetingId);
        if (meeting == null) {
            return Result.error("会议不存在");
        }
        String userId = meeting.getUserId();
        File file = fileService.getFileInfoByMeetingIdAndUserId(meetingId,userId);

        // 封装
        MeetingVo meetingVo = new MeetingVo();
        if (meeting.getId() != null) {
            BeanUtils.copyProperties(meeting, meetingVo);
            String[] files = new String[3];
            if (file != null) {
                files[0] = file.getName();
                files[1] = file.getType();
                files[2] = file.getUrl();
            }
            meetingVo.setFiles(files);
            return Result.success(meetingVo);
        }
        return Result.error("获取会议信息失败");
    }

    /**
     * 保存会议录音文字
     * @param meeting 会议
     */
    @PostMapping("/saveRecording")
    public Result saveRecording(@RequestBody Meeting meeting) {
        String meetingId = meeting.getId();
        String recording = meeting.getRecording();
        int result = meetingService.saveRecording(meetingId, recording);
        if (result > 0) {
            return Result.success();
        }
        return Result.error("保存会议录制失败");
    }

    /**
     * 保存会议总结
     * @param meeting 会议
     * @return 响应
     */
    @PostMapping("/saveAISummary")
    public Result saveAISummary(Meeting meeting) {
        String meetingId = meeting.getId();
        String content = meeting.getContent();
        int result = meetingService.saveAISummary(meetingId, content);
        if (result > 0) {
            return Result.success();
        }
        return Result.error("保存会议总结失败");
    }

    /**
     * 分页查询会议信息
     * @param meetingPageDto 查询条件
     * @return -
     */
    @GetMapping("/user/list")
    public Result userMeetingPage(MeetingPageDto meetingPageDto) {
        return Result.success(meetingService.page(meetingPageDto));
    }

    /**
     * 管理员分页查询会议信息
     * @param adminMeetingPageDto 查询条件
     * @return -
     */
    @GetMapping("/admin/list")
    public Result page(AdminMeetingPageDto adminMeetingPageDto) {
        return Result.success(meetingService.pageAdmin(adminMeetingPageDto));
    }

    /**
     * 根据音频文件创建会议
     */
    @PostMapping("/create/audio")
    public Result createMeetingByAudio(@RequestParam("audio") MultipartFile audioFile) throws Exception {
        String text = TranslatateUtil.translateAudioToText(audioFile);

        // 格式：[{"bg":"550","ed":"3850","onebest":"这是一个测试录音。","speaker":"0"}]
        List<JSONObject> list = JSON.parseArray(text, JSONObject.class);
        String content = null;
        if (list == null)return Result.error("音频为空或音频转文字失败！");
        List<JSONObject> filteredList = list.stream()
                .map(item -> {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("speaker",item.getString("speaker"));
                    jsonObject.put("text",item.getString("onebest"));
                    return jsonObject;
                })
                .toList();
        content = filteredList.toString();

        Meeting meeting = new Meeting();
        meeting.setRecording(content);
        if (meetingService.createMeeting(meeting)==null)return Result.error("创建会议失败");
        return Result.success(meeting);
    }


    /**
     * 获取每个接口都必须的鉴权参数
     *
     * @return
     * @throws SignatureException
     */
    @GetMapping("/auth")
    public static Result getBaseAuthParam(String taskId) throws SignatureException {
        Map<String, String> baseParam = new HashMap<String, String>();
        String ts = String.valueOf(System.currentTimeMillis() / 1000L);
        baseParam.put("app_id", APPID);
        baseParam.put("ts", ts);
        baseParam.put("signa", EncryptUtil.HmacSHA1Encrypt(EncryptUtil.MD5(APPID + ts), SECRET_KEY));
        if (taskId != null) {
            baseParam.put("task_id", taskId);
        }

        return Result.success(baseParam);
    }


}
